package com.heima.media.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {


    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //  参数的非空判断      根据名称分页查询
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        使用mybatisplus推荐的lamda表达式的写法
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank( dto.getName())){
//            构建name模糊查询
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
//        构建分页对象,分页查询一定要添加mybatisPlus的分页插件
        Page<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
//        返回查询结果
        Page<WmChannel> page1 = this.page(page, queryWrapper);
//        构建分页结果对象    分别是：当前页码，每页显示条数，总条数，当前页数据
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        //  参数的非空判断
        if(wmChannel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //  根据名称判断这个频道是否已经存在----->先查询
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());
        WmChannel one = this.getOne(queryWrapper);
        if(one!=null){//代表查到了一个同名的频道
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
            wmChannel.setCreatedTime(new Date());
            this.save(wmChannel);
            return ResponseResult.okResult();
    }
}
